<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { NCard, NForm, NGrid, NFormItemGi, NInput, NTooltip, NInputNumber, NRadioGroup, NRadio, NButton, NSpace, NIcon, useNotification } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { QuestionCircleOutlined } from '@vicons/antd'
import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'
import http from '@/tools/http'

const userStore = useUserStore()

type ParamData = {
    paramCode?: string
    paramName?: string
    paramValue?: string
    paramGroup?: string
    remark?: string
}

type FromData = {
    defaultPasswrod?: string
    lockDuration?: number
    loginFailedCount?: number
    passwordMaxLength?: number
    passwordMinLength?: number
    passwordStrength?: string
}

const paramsData = reactive<ParamData[]>([])

const formRef = ref<FormInst | null>(null)
const formData = reactive<FromData>({
    defaultPasswrod: "123456",
    lockDuration: 0,
    loginFailedCount: 0,
    passwordMaxLength: 32,
    passwordMinLength: 6,
    passwordStrength: "2"
})
const formRule = {
    defaultPasswrod: {
        required: true,
        message: '请输入参数编码',
        trigger: ['input']
    }
}

const title = ref("密码策略")

const dictStore = useDictStore()
const notification = useNotification()

onMounted(() => {
    listPasswordStrategyParams()
})

function openPasswordStrategyEdit() {
    title.value = "密码策略 - 修改"
}

function cancelPasswordStrategyEdit() {
    title.value = "密码策略"
}

function listPasswordStrategyParams() {
    const request = {
        pageSize: 0,
        pageNum: 0,
        paramGroup: "ACCOUNT"
    }
    http.post("/params/page", request).then(({ data }) => {
        paramsData.length = 0
        for (let i = 0; i < data.data.list.length; i++) {
            if (data.data.list[i].paramCode === "ACCOUNT_DEFAULT_PASSWORD") {
                formData.defaultPasswrod = data.data.list[i].paramValue
            }
            if (data.data.list[i].paramCode === "ACCOUNT_LOCK_DURATION") {
                formData.lockDuration = parseInt(data.data.list[i].paramValue)
            }
            if (data.data.list[i].paramCode === "ACCOUNT_LOGIN_FAILED_COUNT") {
                formData.loginFailedCount = parseInt(data.data.list[i].paramValue)
            }
            if (data.data.list[i].paramCode === "ACCOUNT_PASSWORD_MAX_LENGTH") {
                formData.passwordMaxLength = parseInt(data.data.list[i].paramValue)
            }
            if (data.data.list[i].paramCode === "ACCOUNT_PASSWORD_MIN_LENGTH") {
                formData.passwordMinLength = parseInt(data.data.list[i].paramValue)
            }
            if (data.data.list[i].paramCode === "ACCOUNT_PASSWORD_STRENGTH") {
                formData.passwordStrength = data.data.list[i].paramValue
            }
            paramsData.push(data.data.list[i])
        }
    })
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            for (let i = 0; i < paramsData.length; i++) {
                if (paramsData[i].paramCode === "ACCOUNT_DEFAULT_PASSWORD") {
                    paramsData[i].paramValue = formData.defaultPasswrod
                }
                if (paramsData[i].paramCode === "ACCOUNT_LOCK_DURATION") {
                    paramsData[i].paramValue = "" + formData.lockDuration
                }
                if (paramsData[i].paramCode === "ACCOUNT_LOGIN_FAILED_COUNT") {
                    paramsData[i].paramValue = "" + formData.loginFailedCount
                }
                if (paramsData[i].paramCode === "ACCOUNT_PASSWORD_MAX_LENGTH") {
                    paramsData[i].paramValue = "" + formData.passwordMaxLength
                }
                if (paramsData[i].paramCode === "ACCOUNT_PASSWORD_MIN_LENGTH") {
                    paramsData[i].paramValue = "" + formData.passwordMinLength
                }
                if (paramsData[i].paramCode === "ACCOUNT_PASSWORD_STRENGTH") {
                    paramsData[i].paramValue = formData.passwordStrength
                }
            }
            http.post("/params/batch/update", paramsData).then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '修改成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    listPasswordStrategyParams()
                }
            })
        }
    })
    title.value = "密码策略"
}

</script>

<template>
    <div class="flame-container">
        <n-card :bordered="false">
            <n-form style="width:700px" ref="formRef" :model="formData" :rules="formRule" :disabled="title === '密码策略'"
                label-width="180px" require-mark-placement="left" label-placement="left">
                <n-grid :cols="2" :x-gap="10">
                    <n-form-item-gi :span="2" label="新用户默认密码" path="defaultPasswrod">
                        <n-input v-model:value="formData.defaultPasswrod" placeholder="请输入默认密码" type="password"
                            show-password-on="mousedown" :maxlength="32" />
                    </n-form-item-gi>
                    <n-form-item-gi :span="2" label="密码长度" path="passwordMinLength">
                        <n-input-number v-model:value="formData.passwordMinLength" :min="6"
                            :max="formData.passwordMaxLength">
                            <template #prefix>
                                最短
                            </template>
                            <template #suffix>
                                位
                            </template>
                        </n-input-number>
                        <span style="padding: 0 5px;">~</span>
                        <n-input-number v-model:value="formData.passwordMaxLength" :min="formData.passwordMinLength"
                            :max="32">
                            <template #prefix>
                                最长
                            </template>
                            <template #suffix>
                                位
                            </template>
                        </n-input-number>
                    </n-form-item-gi>=
                    <n-form-item-gi :span="2" label="密码强度" path="passwordStrength">
                        <n-space>
                            <n-radio-group v-model:value="formData.passwordStrength">
                                <n-space>
                                    <n-radio v-for="dict in dictStore.dict('ACCOUNT_PASSWORD_STRENGTH')"
                                        :key="dict.value" :value="dict.value">
                                        {{ dict.label }}
                                    </n-radio>
                                </n-space>
                            </n-radio-group>
                            <n-tooltip trigger="hover">
                                <template #trigger>
                                    <div style="display: flex;height: 100%;align-items: center;">
                                        <n-icon size="16">
                                            <question-circle-outlined />
                                        </n-icon>
                                    </div>
                                </template>
                                高：密码中必须包含大写字母、小写字母、数字、特殊字符，至少3种<br>
                                中：密码中必须包含大写字母、小写字母、数字、特殊字符，至少2种<br>
                                低：密码中必须包含大写字母、小写字母、数字、特殊字符，至少1种
                            </n-tooltip>
                        </n-space>
                    </n-form-item-gi>
                    <n-form-item-gi :span="2" label="登录失败触发账号锁定次数" path="loginFailedCount">
                        <n-space>
                            <n-input-number style="width:250px;" v-model:value="formData.loginFailedCount">
                                <template #suffix>
                                    次
                                </template>
                            </n-input-number>
                            <n-tooltip trigger="hover">
                                <template #trigger>
                                    <div style="display: flex;height: 100%;align-items: center;">
                                        <n-icon size="16">
                                            <question-circle-outlined />
                                        </n-icon>
                                    </div>
                                </template>
                                次数为 0 时，登录失败不会锁定账户
                            </n-tooltip>
                        </n-space>
                    </n-form-item-gi>
                    <n-form-item-gi :span="2" label="账号锁定时长（分钟）" path="lockDuration">
                        <n-space>
                            <n-input-number style="width:250px;" v-model:value="formData.lockDuration">
                                <template #suffix>
                                    分钟
                                </template>
                            </n-input-number>
                            <n-tooltip trigger="hover">
                                <template #trigger>
                                    <div style="display: flex;height: 100%;align-items: center;">
                                        <n-icon size="16">
                                            <question-circle-outlined />
                                        </n-icon>
                                    </div>
                                </template>
                                时长为 0 时，登录失败不会锁定账户
                            </n-tooltip>
                        </n-space>
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <template #footer>
                <n-space v-if="userStore.hasAuth('password-strategy:edit')" justify="end">
                    <n-button v-if="title === '密码策略'" @click="openPasswordStrategyEdit">修改</n-button>
                    <n-button v-if="title !== '密码策略'" @click="cancelPasswordStrategyEdit">取消</n-button>
                    <n-button v-if="title !== '密码策略'" @click="submit">保存</n-button>
                </n-space>
            </template>
        </n-card>
    </div>
</template>

<style scoped>
</style>